package com.topvision.common.enumeration;

import org.springframework.core.convert.converter.Converter;
import org.springframework.core.convert.converter.ConverterFactory;

/**
 * @author shengwm
 * @version V0.0.1
 * @Title: UniversalEnumConverterFactory
 * @Package com.topvision.common.enumeration
 * @Description: TODO
 * @date 2017/5/7
 */
public class UniversalEnumConverterFactory implements ConverterFactory<String, BaseEnum> {

    @Override
    public <T extends BaseEnum> Converter<String, T> getConverter(Class<T> targetType) {
        return new StringToEnum(targetType);
    }

    private class StringToEnum<T extends BaseEnum> implements Converter<String, T> {

        private final Class<T> enumType;

        public StringToEnum(Class<T> enumType) {
            this.enumType = enumType;
        }

        public T convert(String source) {
            if (source.length() == 0) {
                return null;
            }
            for (BaseEnum labeledEnum : enumType.getEnumConstants()) {
                if (labeledEnum.getValue().equals(source)||labeledEnum.toString().equals(source)) {
                    return (T) labeledEnum;
                }
            }
            return null;
        }
    }
}
